<template>
  <div class="jsa-template-list">
    <el-card class="page-header">
      <div class="header-content">
        <div class="header-left">
          <h2 class="page-title">
            <el-icon><Document /></el-icon>
            JSA模板管理
          </h2>
          <p class="page-desc">管理不同作业类型的JSA模板，包括工作步骤、潜在危险和控制措施</p>
        </div>
        <div class="header-right">
          <el-button type="primary" @click="handleCreate">
            <el-icon><Plus /></el-icon>
            创建模板
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 筛选条件 -->
    <el-card class="filter-card">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input
            v-model="filters.keyword"
            placeholder="搜索模板名称或作业类型"
            clearable
            @input="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="filters.jobType"
            placeholder="选择作业类型"
            clearable
            @change="handleSearch"
          >
            <el-option
              v-for="jobType in jobTypes"
              :key="jobType"
              :label="jobType"
              :value="jobType"
            />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-select
            v-model="filters.status"
            placeholder="选择状态"
            clearable
            @change="handleSearch"
          >
            <el-option label="启用" :value="true" />
            <el-option label="禁用" :value="false" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-col>
      </el-row>
    </el-card>

    <!-- 模板列表 -->
    <el-card class="table-card">
      <el-table
        v-loading="loading"
        :data="filteredTemplates"
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        
        <el-table-column prop="name" label="模板名称" min-width="150">
          <template #default="{ row }">
            <div class="template-name">
              <span class="name">{{ row.name }}</span>
              <el-tag v-if="!row.isActive" type="info" size="small">已禁用</el-tag>
            </div>
          </template>
        </el-table-column>
        
        <el-table-column prop="jobType" label="作业类型" width="120">
          <template #default="{ row }">
            <el-tag type="primary">{{ row.jobType }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="工作步骤" width="100">
          <template #default="{ row }">
            <el-tag type="success">{{ row.workSteps.length }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="潜在危险" width="100">
          <template #default="{ row }">
            <el-tag type="warning">{{ row.hazards.length }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column label="控制措施" width="100">
          <template #default="{ row }">
            <el-tag type="danger">{{ row.controlMeasures.length }}</el-tag>
          </template>
        </el-table-column>
        
        <el-table-column prop="creator" label="创建人" width="120" />
        
        <el-table-column prop="createTime" label="创建时间" width="160" />
        
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="{ row }">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleView(row)">
                <el-icon><View /></el-icon>
                查看
              </el-button>
              <el-button type="warning" size="small" @click="handleEdit(row)">
                <el-icon><Edit /></el-icon>
                编辑
              </el-button>
              <el-button type="danger" size="small" @click="handleDelete(row)">
                <el-icon><Delete /></el-icon>
                删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 模板详情对话框 -->
    <el-dialog
      v-model="detailVisible"
      title="JSA模板详情"
      width="90%"
      :close-on-click-modal="false"
    >
      <div v-if="currentTemplate" class="template-detail">
        <!-- 基本信息 -->
        <el-card class="detail-section">
          <template #header>
            <div class="section-title">
              <el-icon><Document /></el-icon>
              <span>基本信息</span>
            </div>
          </template>
          <el-descriptions :column="2" border>
            <el-descriptions-item label="模板名称">{{ currentTemplate.name }}</el-descriptions-item>
            <el-descriptions-item label="作业类型">
              <el-tag type="primary">{{ currentTemplate.jobType }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="创建人">{{ currentTemplate.creator }}</el-descriptions-item>
            <el-descriptions-item label="创建时间">{{ currentTemplate.createTime }}</el-descriptions-item>
            <el-descriptions-item label="状态">
              <el-tag :type="currentTemplate.isActive ? 'success' : 'info'">
                {{ currentTemplate.isActive ? '启用' : '禁用' }}
              </el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="更新时间">{{ currentTemplate.updateTime }}</el-descriptions-item>
            <el-descriptions-item label="描述" :span="2">
              {{ currentTemplate.description || '无' }}
            </el-descriptions-item>
          </el-descriptions>
        </el-card>

        <!-- JSA分析表 -->
        <el-card class="detail-section">
          <template #header>
            <div class="section-title">
              <el-icon><List /></el-icon>
              <span>JSA分析表</span>
            </div>
          </template>
          <JSATemplateTable :template="currentTemplate" />
        </el-card>
      </div>
    </el-dialog>

    <!-- 模板表单对话框 -->
    <JSATemplateFormDialog
      v-model="formVisible"
      :template="currentTemplate"
      @success="handleFormSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Search, Refresh, View, Edit, Delete, Document, List, Warning, Lock, Connection, ArrowRight
} from '@element-plus/icons-vue'
import { useJSATemplateStore } from '@/stores/jsTemplate'
import JSATemplateFormDialog from './components/JSATemplateFormDialog.vue'
import JSATemplateTable from './components/JSATemplateTable.vue'
import type { JSATemplate } from '@/types'

const templateStore = useJSATemplateStore()

// 响应式数据
const loading = ref(false)
const detailVisible = ref(false)
const formVisible = ref(false)
const currentTemplate = ref<JSATemplate | null>(null)

// 筛选条件
const filters = ref({
  keyword: '',
  jobType: '',
  status: null as boolean | null
})

// 计算属性
const templates = computed(() => templateStore.getAllTemplates())
const jobTypes = computed(() => templateStore.getJobTypes)

const filteredTemplates = computed(() => {
  let result = templates.value

  // 关键词搜索
  if (filters.value.keyword) {
    const keyword = filters.value.keyword.toLowerCase()
    result = result.filter(template =>
      template.name.toLowerCase().includes(keyword) ||
      template.jobType.toLowerCase().includes(keyword)
    )
  }

  // 作业类型筛选
  if (filters.value.jobType) {
    result = result.filter(template => template.jobType === filters.value.jobType)
  }

  // 状态筛选
  if (filters.value.status !== null) {
    result = result.filter(template => template.isActive === filters.value.status)
  }

  return result
})

// 生命周期
onMounted(() => {
  // 初始化数据
})

// 方法
const handleSearch = () => {
  // 搜索逻辑已在计算属性中实现
}

const handleReset = () => {
  filters.value = {
    keyword: '',
    jobType: '',
    status: null
  }
}

const handleCreate = () => {
  currentTemplate.value = null
  formVisible.value = true
}

const handleView = (template: JSATemplate) => {
  currentTemplate.value = template
  detailVisible.value = true
}

const handleEdit = (template: JSATemplate) => {
  currentTemplate.value = template
  formVisible.value = true
}

const handleDelete = async (template: JSATemplate) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除模板"${template.name}"吗？此操作不可恢复。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    loading.value = true
    await templateStore.deleteTemplate(template.id)
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

const handleFormSuccess = () => {
  ElMessage.success('操作成功')
  loadTemplates() // 刷新模板列表
}

// 辅助方法
const getRiskLevelType = (level: string) => {
  const types = {
    low: 'success',
    medium: 'warning',
    high: 'danger',
    critical: 'danger'
  }
  return types[level as keyof typeof types] || 'info'
}

const getRiskLevelText = (level: string) => {
  const texts = {
    low: '低风险',
    medium: '中风险',
    high: '高风险',
    critical: '极高风险'
  }
  return texts[level as keyof typeof texts] || level
}

const getCategoryType = (category: string) => {
  const types = {
    prevention: 'primary',
    protection: 'warning',
    emergency: 'danger'
  }
  return types[category as keyof typeof types] || 'info'
}

const getCategoryText = (category: string) => {
  const texts = {
    prevention: '预防措施',
    protection: '保护措施',
    emergency: '应急措施'
  }
  return texts[category as keyof typeof texts] || category
}
</script>

<style lang="scss" scoped>
.jsa-template-list {
  .page-header {
    margin-bottom: 20px;
    
    .header-content {
      display: flex;
      justify-content: space-between;
      align-items: flex-start;
      
      .header-left {
        .page-title {
          display: flex;
          align-items: center;
          gap: 8px;
          margin: 0 0 8px 0;
          font-size: 20px;
          font-weight: 500;
          color: #303133;
        }
        
        .page-desc {
          margin: 0;
          color: #606266;
          font-size: 14px;
        }
      }
    }
  }
  
  .filter-card {
    margin-bottom: 20px;
  }
  
  .table-card {
    .template-name {
      display: flex;
      align-items: center;
      gap: 8px;
      
      .name {
        font-weight: 500;
      }
    }
    
    .action-buttons {
      display: flex;
      gap: 8px;
      flex-wrap: nowrap;
      
      .el-button {
        min-width: 60px;
        padding: 5px 8px;
        
        .el-icon {
          margin-right: 4px;
        }
      }
    }
  }
  
  .template-detail {
    .detail-section {
      margin-bottom: 20px;
      
      .section-title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-weight: 500;
      }
    }
    
    .steps-list {
      .step-item {
        display: flex;
        align-items: flex-start;
        gap: 12px;
        padding: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 6px;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .step-number {
          display: flex;
          align-items: center;
          justify-content: center;
          width: 24px;
          height: 24px;
          background: #409eff;
          color: white;
          border-radius: 50%;
          font-size: 12px;
          font-weight: 500;
          flex-shrink: 0;
        }
        
        .step-content {
          flex: 1;
          
          .step-name {
            font-weight: 500;
            margin-bottom: 4px;
          }
          
          .step-description {
            color: #606266;
            font-size: 14px;
          }
        }
      }
    }
    
    .hazards-list, .measures-list {
      .hazard-item, .measure-item {
        padding: 12px;
        border: 1px solid #e4e7ed;
        border-radius: 6px;
        margin-bottom: 8px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        .hazard-header, .measure-header {
          display: flex;
          align-items: center;
          gap: 8px;
          margin-bottom: 4px;
          
          .hazard-name, .measure-name {
            font-weight: 500;
            flex: 1;
          }
        }
        
        .hazard-description, .measure-description {
          color: #606266;
          font-size: 14px;
        }
      }
    }
    
    .relations-container {
      .relation-section {
        margin-bottom: 20px;
        
        &:last-child {
          margin-bottom: 0;
        }
        
        h4 {
          margin: 0 0 12px 0;
          color: #303133;
          font-size: 14px;
          font-weight: 500;
        }
        
        .relation-list {
          .relation-item {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 8px 12px;
            background: #f5f7fa;
            border-radius: 4px;
            margin-bottom: 8px;
            
            &:last-child {
              margin-bottom: 0;
            }
            
            .relation-from, .relation-to {
              flex: 1;
              font-size: 14px;
            }
            
            .relation-arrow {
              color: #409eff;
            }
          }
        }
      }
    }
  }
}
</style>
